package com.nowcoder.community;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.nowcoder.community.dao.DiscussPostMapper;
import com.nowcoder.community.dao.elasticsearch.DiscussPostRepository;
import com.nowcoder.community.entity.DiscussPost;
import com.tdunning.math.stats.Sort;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.elasticsearch.core.query.HighlightQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;

import java.io.IOException;
import java.lang.annotation.Native;
import java.util.LinkedList;
import java.util.List;


/**
 * <p>Title: EStests</p>
 * <p>author 12427</p>
 *
 * @version ver1.0
 * @date 2022/8/22 17:48
 */
@RunWith(SpringRunner.class)
@SpringBootTest
@ContextConfiguration(classes = CommunityApplication.class)
public class EStests {

    @Autowired
    private DiscussPostMapper discussPostMapper ;

    @Autowired
    private DiscussPostRepository discussPostRepository ;
//
//    @Autowired
//    private ElasticsearchTemplate elasticsearchTemplate ;

    @Autowired
    @Qualifier("client")
    private RestHighLevelClient restHighLevelClient ;

    // 添加数据
    @Test
    public void testInsert(){
        discussPostRepository.save(discussPostMapper.selectDiscussPostById(241)) ;
        discussPostRepository.save(discussPostMapper.selectDiscussPostById(242)) ;
        discussPostRepository.save(discussPostMapper.selectDiscussPostById(243)) ;
    }


    @Test
    public void testInsertList(){
        discussPostRepository.saveAll(discussPostMapper.selectDiscussPosts(101 , 0 , 100 , 0 )) ;
        discussPostRepository.saveAll(discussPostMapper.selectDiscussPosts(102 , 0 , 100, 0)) ;
        discussPostRepository.saveAll(discussPostMapper.selectDiscussPosts(103 , 0 , 100, 0)) ;
        discussPostRepository.saveAll(discussPostMapper.selectDiscussPosts(111 , 0 , 100, 0)) ;
        discussPostRepository.saveAll(discussPostMapper.selectDiscussPosts(112 , 0 , 100, 0)) ;
        discussPostRepository.saveAll(discussPostMapper.selectDiscussPosts(131 , 0 , 100, 0)) ;
        discussPostRepository.saveAll(discussPostMapper.selectDiscussPosts(132 , 0 , 100, 0)) ;
        discussPostRepository.saveAll(discussPostMapper.selectDiscussPosts(134 , 0 , 100, 0)) ;
    }


    // 修改
    @Test
    public void testUpdate(){
        DiscussPost post = discussPostMapper.selectDiscussPostById(231) ;
        post.setContent("我是新人，使劲灌水") ;
        discussPostRepository.save(post) ;
    }

    // 删除
    @Test
    public void testDelete(){
//        discussPostRepository.deleteById(231);

        discussPostRepository.deleteAll();
    }


    @Test
    public void highLightQuery() throws IOException {
        SearchRequest searchRequest = new SearchRequest("discusspost") ;  // discusspost 是 索引名， 就相当于表名

        // 高亮
        HighlightBuilder highlightBuilder = new HighlightBuilder() ;
        highlightBuilder.field("title") ;
        highlightBuilder.field("content") ;
        highlightBuilder.requireFieldMatch(false) ;
        highlightBuilder.preTags("<span style='color:red'>") ;
        highlightBuilder.postTags("</span>") ;

        // 构造搜索条件
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder()
                .query(QueryBuilders.multiMatchQuery("互联网寒冬" , "title" , "content"))
                .sort(SortBuilders.fieldSort("type").order(SortOrder.DESC))
                .sort(SortBuilders.fieldSort("score").order(SortOrder.DESC))
                .sort(SortBuilders.fieldSort("createTime").order(SortOrder.DESC))
                .from(0)
                .size(10)
                .highlighter(highlightBuilder) ;

        searchRequest.source(searchSourceBuilder) ;
        SearchResponse searchResponse  = restHighLevelClient.search(searchRequest , RequestOptions.DEFAULT) ;

        List<DiscussPost> list = new LinkedList<>() ;
        for (SearchHit hit : searchResponse.getHits().getHits()){
            DiscussPost discussPost = JSONObject.parseObject(hit.getSourceAsString() , DiscussPost.class) ;

            // 处理高亮显示结果
            HighlightField titleField = hit.getHighlightFields().get("title") ;
            if(titleField != null){
                discussPost.setTitle(titleField.getFragments()[0].toString());
            }
            HighlightField contentField = hit.getHighlightFields().get("content") ;
            if(contentField != null){
                discussPost.setContent(contentField.getFragments()[0].toString());
            }
            System.out.println(discussPost);
            list.add(discussPost) ;
        }

    }

}
